package com.cqhz.quwan.ui.main.order

import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.PushOrderItemBean
import com.cqhz.quwan.model.PushOrderResultBean
import com.cqhz.quwan.mvp.buy.MyPushOrderContract
import com.cqhz.quwan.mvp.buy.MyPushOrderPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.mine.ExpertCertificationActivity
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.CommonDecoration
import com.cqhz.quwan.util.formatMoney
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_my_push_order.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 我的推单
 * Created by Guojing on 2018/10/29.
 */
class MyPushOrderActivity : GoBackActivity(), MyPushOrderContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var myPushOrderPresenter: MyPushOrderPresenter
    private var loginBean: LoginBean? = null
    private var type: Int = 1// 1：近7日 2：近30日
    private var titles = arrayOf("中奖推单", "待开推单", "未中推单")
    private var pages = ArrayList<View>()
    private var pagesIndex = ArrayList<Int>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var orders = ArrayList<ArrayList<PushOrderItemBean>>()

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "我的推单"
    }

    override fun layout(): Int {
        return R.layout.activity_my_push_order
    }

    override fun initView() {
        myPushOrderPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }

        setTitleBarRightText("认证", ({
            startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else ExpertCertificationActivity::class.java))
        }))

        // 初始化页面元素和相应数据以及适配器
        for (i in 1..titles.size) {
            initAdapter(i)
        }
        initPager()

        rg_select_status.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.action_select_week -> type = 1
                R.id.action_select_mouth -> type = 2
            }

            vp_content.currentItem = 1
            refreshCurrentPage(1)
        }

        // 加载数据
        vp_content.currentItem = 1
        refreshCurrentPage(1)
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter(position: Int) {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)
        var pageIndex = 1

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var orderList = ArrayList<PushOrderItemBean>()
        var orderListAdapter = CommonAdapterHelper.getPushOrderListAdapter(orderList, position)
        orderListAdapter.emptyView = emptyView

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.addItemDecoration(CommonDecoration(1))
        holder.rvContent.adapter = orderListAdapter
        orderListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (orders[currentPage].size > 0) {
                if (orders[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = orders[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    myPushOrderPresenter.getOrderList(loginBean!!.userId!!, type, currentPage, pageNo, KeyContract.pageSize)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                refreshCurrentPage(currentPage)
            }
        }, holder.rvContent)
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as PushOrderItemBean

                val intent = Intent(context(), WebViewActivity::class.java)
                intent.putExtra(KeyContract.Title, "订单详情")
                val url = "${API.DDXQ}?id=${item.orderId}"
                intent.putExtra(KeyContract.Url, url)
                intent.putExtra(KeyContract.EnableRefresh, false)
                startActivity(intent)
            }
        })
        // 刷新
        holder.refreshLayout.setOnRefreshListener {
            var currentPage = vp_content.currentItem
            refreshCurrentPage(currentPage)
        }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        pagesIndex.add(pageIndex)
        holders.add(holder)
        orders.add(orderList)
        adapters.add(orderListAdapter)
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (orders[position].size <= 0) {
                    refreshCurrentPage(position)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage(currentPage: Int) {
        if (loginBean != null) {
            myPushOrderPresenter.getOrderList(loginBean!!.userId!!, type, currentPage, 1, KeyContract.pageSize)
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
        }
    }

    override fun loadOrderList(currentPage: Int, pageNo: Int, bean: PushOrderResultBean) {
        tv_hit_number.text = bean.hitOrders
        tv_hit_rate.text = bean.hitOdds.formatMoney() + "%"
        tv_profit_rate.text = bean.profitOdds + "%"
        tv_red_number.text = bean.reds + "连中"

        if (pageNo == 1) {
            orders[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader!!) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (bean.orderPage.records.isNotEmpty()) {
            orders[currentPage].addAll(bean.orderPage.records)
        }

        if (bean.orderPage.total > orders[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onDestroy() {
        super.onDestroy()
        myPushOrderPresenter.detachView()
    }
}
